﻿using Common.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

namespace Common.LogHelper
{
    public class LogLock
    {
        static ReaderWriterLockSlim _LogWriteLock = new ReaderWriterLockSlim();
        static int _writedCount = 0;
        static int _failCount = 0;
        static string _contentRoot = string.Empty;
        public LogLock(string contentPath)
        {
            _contentRoot = contentPath;
        }

        public static void OutSql2Log(string prefix, string[] dataParas, bool IsHeader = true)
        {
            try
            {
                //设置读写锁为写入模式独占资源，其他写入请求需要等待本次写入结束之后才能继续写入
                //注意：长时间持有写线程锁或写线程锁会使其他线程发生饥饿，在此处进行写入模式仅是为了降低代码复杂度
                //      因进入与退出写入模式应在同一个try finally 语句块内，所以在请求进入写入模式之前不能触发异常，否则释放次数大于请求次数将会触发异常
                _LogWriteLock.EnterWriteLock();
                var folderPath = Path.Combine(_contentRoot, "Log");
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                var logFilePath = FileHelper.GetAvailabelFileWithPrefixOrderSize(folderPath, prefix);
                var now = DateTime.Now;
                string logContent = String.Join("\r\n", dataParas);
                if (IsHeader)
                {
                    logContent = (
                            "-----------------------------\r\n"+
                            DateTime.Now+"|\r\n"+
                            logContent+"\r\n"
                        );
                }
                File.AppendAllText(logFilePath, logContent);
                _writedCount++;
            }
            catch(Exception e)
            {
                Console.Write(e.Message);
                _failCount += 1;
            }
            finally
            {
                //退出写入模式，释放资源占用
                //注意：一次请求对应一次释放
                //      若释放次数大于请求次数将会触发异常[写入锁定未经保持即被释放]
                //      若请求处理完成后未释放将会触发异常[此模式下不允许递归方式写入错定]
                _LogWriteLock.ExitWriteLock();
            }

        }
    }
}
